package com.zwf.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zwf.constant.MessageConstant;
import com.zwf.constant.PasswordConstant;
import com.zwf.constant.StatusConstant;
import com.zwf.context.BaseContext;
import com.zwf.dto.EmployeeDTO;
import com.zwf.dto.EmployeeLoginDTO;
import com.zwf.dto.EmployeePageQueryDTO;
import com.zwf.dto.PasswordEditDTO;
import com.zwf.entity.Employee;
import com.zwf.exception.AccountLockedException;
import com.zwf.exception.AccountNotFoundException;
import com.zwf.exception.PasswordEditFailedException;
import com.zwf.exception.PasswordErrorException;
import com.zwf.mapper.EmployeeMapper;
import com.zwf.result.PageResult;
import com.zwf.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            log.info("输入密码{}，真实密码{}",password,employee.getPassword());
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        Employee employee=new Employee();

        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

        //设置账号状态
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

//        //设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //设置当前记录的创建人id和修改人id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.add(employee);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page=employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> result = page.getResult();
        PageResult pageResult=new PageResult(total,result);
        return pageResult;
    }

    /**
     * 启用禁用员工账号
     *
     * @param status
     * @param id
     */
    @Override
    public void enAndDisAccount(Integer status, Long id) {
        //TODO 修改时间和修改人
        Employee employee=Employee.builder()
                        .status(status)
                        .id(id)
                        .build();
        employeeMapper.update(employee);

    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee queryById(Long id) {
        Employee employee=employeeMapper.query(id);
        return employee;
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void edit(EmployeeDTO employeeDTO) {
        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employeeMapper.update(employee);
    }

    /**
     * 修改员工密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //获取当前登录用户的id
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        String password = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        Employee employee = employeeMapper.query(passwordEditDTO.getEmpId());
        if(!employee.getPassword().equals(password)){
            throw new PasswordEditFailedException(MessageConstant.OLD_PASSWORD_ERROP);
        }
        if(passwordEditDTO.getNewPassword().equals(passwordEditDTO.getOldPassword())){
            throw new PasswordEditFailedException(MessageConstant.OLD_PASSWORD_EQUAL_NEW_PASSWORD);
        }
        Employee emp=Employee.builder()
                .id(passwordEditDTO.getEmpId())
                        .password(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()))
                                .build();
        employeeMapper.update(emp);
    }
}
